package cn.growthgate.fgo.config;

import java.util.ArrayList;
import java.util.List;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.baomidou.mybatisplus.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.plugins.parser.ISqlParser;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantHandler;
import com.baomidou.mybatisplus.plugins.parser.tenant.TenantSqlParser;

import cn.growthgate.fgo.util.AuthenticationUtils;
import cn.growthgate.fgo.util.StringUtils;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

/**
 * Mybatis-Plus配置
 * 
 * @author GrowthGate
 * @since 2019年4月12日
 *
 */
@Configuration
public class MybatisPlusConfig {

	@Bean
	public PaginationInterceptor paginationInterceptor() {
		PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
		paginationInterceptor.setLocalPage(true);
		// 多租户
		List<ISqlParser> sqlParsers = new ArrayList<>();
		TenantSqlParser tenantSqlParser = new TenantSqlParser();
		tenantSqlParser.setTenantHandler(new TenantHandler() {

			@Override
			public String getTenantIdColumn() {
				return "userId";
			}

			@Override
			public Expression getTenantId() {
				Long loginUserId = AuthenticationUtils.getLoginUserId();
				return loginUserId != null ? new LongValue(loginUserId) : null;
			}

			@Override
			public boolean doTableFilter(String tableName) {
				// 过滤表
				return !StringUtils.equalsAny(tableName, "t_my_servant", "t_my_item");
			}

		});
		sqlParsers.add(tenantSqlParser);
		paginationInterceptor.setSqlParserList(sqlParsers);
		return paginationInterceptor;
	}

}
